import 'dart:async';
import 'dart:ui';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:saas_warning_package/saas_warning_package.dart';
import '../config/global_configs.dart';
import '../util/speak_text_service.dart';

String notificationChannelId = '报警接受服务';

var notificationId = 888;

ServiceInstance? currentService;

class SosWarningService {
  static SosWarningService? _instance;

  static SosWarningService get instance => _instance ??= SosWarningService._();

  SosWarningService._();

  FlutterBackgroundService? service;

  Future<void> initService() async {
    if (service != null) {
      return;
    }

    service = FlutterBackgroundService();

    AndroidNotificationChannel channel = AndroidNotificationChannel(
      notificationChannelId, // id
      '报警接受服务', // title
      description: '报警消息接受服务', // description
      importance: Importance.low, // importance must be at low or higher level
    );

    final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await service?.configure(
        androidConfiguration: AndroidConfiguration(
          // this will be executed when app is in foreground or background in separated isolate
          onStart: onStart,
          // auto start service
          autoStart: false,
          isForegroundMode: true,
          notificationChannelId: notificationChannelId,
          // this must match with notification channel you created above.
          initialNotificationTitle: '报警接受服务',
          initialNotificationContent: '报警消息接受服务',
          foregroundServiceNotificationId: notificationId,
        ),
        iosConfiguration: IosConfiguration(
          autoStart: false,
          onForeground: onStart,
          // onBackground: onIosBackground,
        ));
  }

  Future<bool> startService() async {
    print("开启服务1");
    var result = await service?.startService();
    return result??false;
  }

  void stopService() {
    service?.invoke("stop");
    currentService = null;
    SaasWarningPackage.instance.dispose();
  }

  void setReceiveArea(List<int> typeIds,List<SosBuildingData> buildingList){
    service?.invoke("setReceiveArea",
        {"typeIds": typeIds, "buildingList": buildingList.map((e) => e.toMap()).toList()});
  }

  void sendUrlMsg(String url, String branchId, {String? accountName}) {
    service?.invoke("setUrl",
        {"url": url, "branchId": branchId, "accountName": accountName});
  }

  void sendEnableReceive(bool enable) {
    service?.invoke("sendEnableReceive", {"enable": enable});
  }

  void sendSosMsg(String msg, {CallWarningData? callInfo}) {
    currentService?.invoke("sosMsg", {"msg": msg, "callInfo": callInfo?.toMap()});
  }

  void sendHandle(CallWarningData callInfo) {
    currentService?.invoke("sendHandle", {"callInfo": callInfo.toMap()});
  }

  void reconnect() {
    service?.invoke(
      "reconnect",
    );
  }

  void sendBranchId(String branchId) {
    service?.invoke("sendBranchId", {"branchId": branchId});
  }
}

@pragma('vm:entry-point')
Future<void> onStart(ServiceInstance service) async {
  var canReceive = true;
  List<dynamic> typeIds = [];
  List<SosBuildingData> buildingIds = [];

  // Only available for flutter 3.0.0 and later
  print("12312312313");
  DartPluginRegistrant.ensureInitialized();
  HttpUtil.instance;
  currentService = service;
  service.invoke("serviceStart");
  // SaasWarningPackage.instance.setReceiveListener(
  //     receiveWarningCall: (info) {
  //       if (canReceive) {
  //         SpeakTextService.speak(info.speechMsg??"");
  //         SosWarningService.instance.sendSosMsg(info.speechMsg??"", callInfo: info);
  //       }
  //     },
  //     receiveWarningHandle: (info) {
  //       SosWarningService.instance.sendHandle(info);
  //     },
  //     receiveMapInfo: (map) {});
  SaasWarningPackage.instance.setReceiveListener(
      receiveWarningCall: (info) {
        if (canReceive) {
          var fitBuilding = buildingIds.where((element) => element.buildingId.toString()==info.buildingId.toString()).toList();
          if(fitBuilding.isNotEmpty){
            if(info.floorId==null){
              if(typeIds.contains(info.callType)||typeIds.contains(info.alarmType)){
                SpeakTextService.speak(info.speechMsg??"");
                SosWarningService.instance.sendSosMsg(info.speechMsg??"", callInfo: info);
              }
            }else{
              if((fitBuilding.first.floorIds??[]).map((e) => e.toString()).toList().contains(info.floorId.toString())){
                if(typeIds.contains(info.callType)||typeIds.contains(info.alarmType)){
                  SpeakTextService.speak(info.speechMsg??"");
                  SosWarningService.instance.sendSosMsg(info.speechMsg??"", callInfo: info);
                }
              }
            }
          }
        }
      },
      receiveWarningHandle: (info) {
        SosWarningService.instance.sendHandle(info);
      },
      receiveMapInfo: (map) {});
  service.on("stop").listen((event) {
    SaasWarningPackage.instance.dispose();
    service.stopSelf();
  });

  service.on("setUrl").listen((event) {
    if(event==null){
      return;
    }
    var url = event!["url"];
    var branchId = event["branchId"];
    var accountName = event["accountName"];
    // DataSocketUtils.baseUrl = url;
    // DataSocketUtils.instence.init();
    print("startService==>6666");
    SaasWarningPackage.instance.initUrl(url, account: accountName);
    SaasWarningPackage.instance.initBranchId(branchId);
    SaasWarningPackage.instance.connectSocket();
  });

  service.on("sendEnableReceive").listen((event) {
    if(event!=null){
      canReceive = event!["enable"];
    }
  });

  service.on("reconnect").listen((event) {
    // DataSocketUtils.instence.resetConnect();
    SaasWarningPackage.instance.connectSocket();
  });

  service.on("setReceiveArea").listen((event) {
    typeIds = event!['typeIds'] ;
    buildingIds = ((event['buildingList'] as List)??[]).map((e) => SosBuildingData.fromMap(e)).toList();
    print("selectTypes===${typeIds}");
  });

  service.on("sendBranchId").listen((event) {
    var branchId = event!["branchId"].toString();
    // DataSocketUtils.instence.branchId = branchId;
    SaasWarningPackage.instance.initBranchId(branchId);
  });
}

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  print("开启服务3");

  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();
  currentService = service;
  await SpUtil.getInstance();
  var url = SpUtil.getString("url");
  var humanId = SpUtil.getInt("humanId");
  var branchId = SpUtil.getString("branchId");

  debugPrint(
      "url::${url}\nhumanId::${humanId}\nbranchId::${branchId}===>${SaasWarningPackage.instance.baseUrl}");

  SaasWarningPackage.instance.initUrl(url??"");
  SaasWarningPackage.instance.initBranchId(branchId??"");
  // SaasWarningPackage.humanId = humanId;
  SaasWarningPackage.instance.connectSocket();

  service.invoke("serviceStart");

  // SaasWarningPackage.instance.setReceiveListener(
  //     receiveWarningCall: (info) {
  //       SpeakTextService.speak(info.speechMsg??"");
  //       SosWarningService.instance.sendSosMsg(info.speechMsg??"", callInfo: info);
  //     },
  //     receiveWarningHandle: (info) {
  //       SosWarningService.instance.sendHandle(info);
  //     },
  //     receiveMapInfo: (map) {});

  service.on("stop").listen((event) {
    service.stopSelf();
  });

  service.on("sendUserId").listen((event) {
    var humanId = event!["humanId"];
    print("humanId===>${humanId}");
    // SaasWarningPackage.humanId = humanId;
  });

  service.on("sendBranchId").listen((event) {
    var branchId = event!["branchId"].toString();
    SaasWarningPackage.instance.initBranchId(branchId);
  });

  service.on("setUrl").listen((event) {
    var url = event!["url"];
    var humanId = event["humanId"];
    // SaasWarningPackage.humanId = humanId;
    SaasWarningPackage.instance.initUrl(url);
    SaasWarningPackage.instance.connectSocket();
  });

  service.on("reconnect").listen((event) {
    // DataSocketUtils.instence.resetConnect();
    SaasWarningPackage.instance.connectSocket();
  });
  return true;
}
